var calendarController = new Class({
	Implements: Events,
	onLoadEnds: {},
	calTable: {},
	container: {},
	todayBtn: {},
	mTitle: {},
	curCalDate: false,
	today: new Date().clearTime(),
	calData: [],
	selCtrl: {},
	autoActivate: true,
	activeElement: {},
	mainRequest: false,
	initialize: function(container, table, selCtrl)
	{
		this.container = container;
		this.calTable = table;
		this.selCtrl = selCtrl;
		this.selCtrl.calCtrl = this;
		this.todayBtn = this.calTable.getElement('.todayBtn');
		this.prevMonthBtn = this.calTable.getElement('.arrowLeft');
		this.nextMonthBtn = this.calTable.getElement('.arrowRight');
		this.mTitle = this.calTable.getElement('.monthTitle');
		this.load();	
		
		this.nextMonthBtn.addEvent('click', function(e){
			e.preventDefault();
			if(typeof this.curCalDate.increment != 'function')
				return;			
			this.curCalDate = this.curCalDate.increment('month', 1);
			this.load();
		}.bind(this));
		
		this.prevMonthBtn.addEvent('click', function(e){
			e.preventDefault();
			if(typeof this.curCalDate.decrement != 'function')
				return;			
			this.curCalDate = this.curCalDate.decrement('month', 1);
			this.load();
		}.bind(this));
		
		this.todayBtn.addEvent('click', function(e){
			e.preventDefault();

			this.curCalDate = new Date().clearTime();
			this.load();
		}.bind(this));
		
		this.shortcuts();
	},
	load: function(autoActivate){
		
		this.autoActivate = (autoActivate == null || autoActivate === true) ? true : autoActivate;
		if(this.srchCtrl)this.srchCtrl.clear();
		if(this.selCtrl)this.selCtrl.removeContent();
		var yearmonth = (this.curCalDate) ? '|' + this.curCalDate.format('%Y|%m') : '';
		
		if(!this.mainRequest)
		this.mainRequest = new Request.JSON({ url: api + 'calendar.json' + yearmonth,
			onRequest: function(){
				this.container.spin();
			}.bind(this),
			onSuccess: function(json, text){
				if(json)
					this.calData = json;
				else
					this.calData = null;
				this.setTimeLine();
				
			}.bind(this),
			onComplete: function(){
				this.container.unspin();
			}.bind(this)
		}).send();
		else {
			if(this.mainRequest.isRunning())
				return false;
			this.mainRequest.setOptions({url: api + 'calendar.json' + yearmonth});
			this.mainRequest.send();
		}
	},
	setTimeLine: function(){
		this.container.empty();
		if(!this.calData)
			return false;
			
		this.curCalDate = new Date().parse(this.calData.date);
		
		if(this.today.format('%Y-%m-01') == this.curCalDate.format('%Y-%m-%d'))
			this.todayBtn.fade('hide');
		else
			this.todayBtn.fade('show');
		
		this.mTitle.set('html', this.curCalDate.format('%Y. %B').toLowerCase());
		
		this.buildCalCells();		
		this.fireEvent('loadends');	
	},
	buildCalCells: function(){
		var self = this;
		var dl = new Element('dl.calCells');
		$H(this.calData.caldays).each(function(day, date){
			var dt = new Element('dt', {'date' : date}).store('content', this);
			
			if(date == this.today.format('%Y-%m-%d'))
				dt.addClass('celToday');
				
			if(this.curCalDate.format('%Y-%m') != new Date().parse(date).format('%Y-%m'))
				dt.addClass('celOtherMonth');
			
			var dayNum = (new Date().parse(date).format('%d').toInt());
			
			new Element('span', {text: dayNum}).inject(dt);
			var ul = new Element('ul').inject(dt);
			
			var vday = (day.length > 4) ? day.slice(0, 4) : day;
			vday.each(function(item, key){
				var li;
				sname = item.series.seriesname;
				sseasxep = item.seasonnumber + 'x' + sprintf('%02d', item.episodenumber.toInt()) + ' ';
				if((sname.length+sseasxep.length) > 12)
				{
					r = new RegExp("^(.{" + (12-sseasxep.length) + "})(.*)$", "i");
					sname = sname.replace(r,"$1").trim() + '...';
				}
				li = new Element('li', {text: sseasxep+sname}).inject(ul);
				if((userstatus.isLoggedin && 'watchlist' in userstatus.userData.user_settings && userstatus.userData.user_settings.watchlist.contains(item.id)))
					li.addClass('watched');
				else if((userstatus.isLoggedin && 'downloadlist' in userstatus.userData.user_settings && userstatus.userData.user_settings.downloadlist.contains(item.id)))
					li.addClass('downloaded');
					
				if((item.series.seriesname.length+sseasxep.length) > 12){
					var ltext = new Element('span', {text: sseasxep + item.series.seriesname});
					li.addEvents({
						mouseenter: function(){
							this.addClass('h');
							ltext.inject(li);
							self.scrollText.run(li.getSize().x, ltext);
						},
						mouseleave: function(){
							this.removeClass('h');
							ltext.dispose();
							ltext.stop();
						}
					});
				}	
				if(userstatus.isLoggedin && userstatus.preferences.callView == 1 && !item.checked) 
					li.addClass('notfollowed');				
			});
			
			var c = day.length;
			if(c > 4) {
				c = c - 4;	
				var li = new Element('li', {html: 'm&eacute;g ' + c + '...', 'class':'viewMore'}).inject(ul);
			}	
			
			dt.activate = this.activate;	
			this.setCalCellEvents(dt);
			dt.inject(dl);
			if(date == this.autoActivate)
				dt.activate();
		}.bind(this));
		dl.inject(this.container);
		if(this.autoActivate === true)
			this.activateStartup();
	},
	scrollText: function(contWidth)
	{
		var w = this.getSize().x;
		var p = (function(){
			var l = this.getStyle('left').toInt();
			if(w+l < contWidth)
				this.setStyle('left', 12);
			else
				this.setStyle('left', l-12);
		}).periodical(500, this);
		this.stop = function(){p=$clear(p);this.stop = $empty();this.setStyle('left', 12);};
	},
	setCalCellEvents: function(dt)
	{
		if(!dt)
			return;
		var self = this;	
		dt.addEvents({
			mousedown: function(e){
				e.preventDefault();
			},
			click: function(e){
				e.preventDefault();
				this.activate();		
			}
		});			
	},
	activateStartup: function(){
		if(this.container.getElement('.celToday'))
			this.container.getElement('.celToday').activate();
		else
			this.container.getElement('.calCells').getFirst('dt').activate();
	},
	activate: function(){
		var self = this.retrieve('content');
		self.srchCtrl.clear();
		if(typeOf(self.activeElement) == 'element')
			self.activeElement.removeClass('active');
			
		self.activeElement = this;
		
		this.addClass('active');
		self.selCtrl.removeContent();
		self.selCtrl.setContent(self.calData.caldays[this.getProperty('date')], this);
		
		if(userstatus.isLoggedin && userstatus.userData && userstatus.userData.user_settings && userstatus.userData.user_settings.user_series && !userstatus.userData.user_settings.user_series.length && self.selCtrl && !self.selCtrl.container.get('text').length)
		{
			new Element('span', {
				'class' : 'helpText',
				'html' : 'A sorozatok k&ouml;vet&eacute;s&eacute;hez el&#x151;sz&ouml;r ki kell v&aacute;lasztanod a sorozatokat.<br/>Ezt a fenti keres&#x151;, vagy a jobb fent tal&aacute;lhat&oacute; &bdquo;Folytat&oacute;d&oacute; &eacute;s k&ouml;vetett sorozatok&rdquo; ikonra kattintva megjelen&#x151; sorozat c&iacute;mek mellett tal&aacute;lhat&oacute; &bdquo;K&ouml;vet&eacute;s&rdquo; ikonra kattintva teheted meg.'
			}).inject(self.selCtrl.container);
		}
		else {
			new Element('span', {'class' : 'monoscope'}).inject(self.selCtrl.container);
		}
		
	},
	deactivate: function(){
		if(typeOf(this.activeElement) == 'element')
		{
			this.activeElement.removeClass('active');
			this.activeElement = $empty();
		}
	},
	shortcuts: function(){
		var self = this;
		var moveActive = function(e){
			var e = new Event(e);
	
			if(['input', 'textarea'].contains($(e.target).get('tag')))
				return true;
			
			e.preventDefault();
				
			if(!this.curCalDate)
				return true;
			var times = 1;
			var direction = +1;
			var nextElement = $empty();
			var fallbackActive = $empty();
			var celToday = this.container.getElement('.celToday');
			
			switch(e.key)
			{
				case "right":
					nextElement = (this.activeElement) ? this.activeElement.getNext('dt') : $empty();
					fallbackActive = (celToday) ? celToday : this.container.getElement('dt');
				break;
				
				case "left":
					direction = -1;
					nextElement = (this.activeElement) ? this.activeElement.getPrevious('dt') : $empty();
					fallbackActive = (celToday) ? celToday : this.container.getElement('dl > dt:last-child');
				break;

				case "up":
					direction = -1;
					times = 7;
					nextElement = (this.activeElement) ? (this.activeElement.getAllPrevious('dt').length > 5) ? this.activeElement.getAllPrevious('dt')[6] : $empty() : $empty();
					fallbackActive = (celToday) ? celToday : this.container.getElement('dl > dt:last-child');
				break;

				case "down":
					times = 7;
					nextElement = (this.activeElement) ? (this.activeElement.getAllNext('dt').length > 5) ? this.activeElement.getAllNext('dt')[6] : $empty() : $empty();
					fallbackActive = (celToday) ? celToday : this.container.getElement('dt');
				break;
			}
								
			if(typeOf(this.activeElement) == 'element')
			{			
				if(nextElement)
					nextElement.activate();
				else
				{
					var activeDate = new Date().parse(this.activeElement.getProperty('date'));
					
					this.curCalDate = (direction > 0) ? this.curCalDate.increment('month', 1) : this.curCalDate.decrement('month', 1);
					
					this.addEvent('loadends', function(){
						
						var nextDate = ((direction > 0) ? activeDate.increment('day', times) : activeDate.decrement('day', times)).format('%Y-%m-%d');
						
						var nextDay = this.container.getElement('dt[date="' + nextDate + '"]');
						if(nextDay)
							nextDay.activate();
					});
					this.load(false);
				}	
			}
			else if(fallbackActive) {
				fallbackActive.activate();
			}
			
		};
		
		this.keyboardShortcuts = k;
		this.keyboardShortcuts.addEvents({ 
			right:moveActive.bind(this),
			left:moveActive.bind(this),
			up:moveActive.bind(this),
			down:moveActive.bind(this)
		});
		this.mTitle.addEvents({
			click: function(e){if(e.alt == true)self.load();},
			mouseenter: function(e){if(e.alt == true)this.addClass('mover');},
			mouseleave: function(e){if(this.hasClass('mover'))this.toggleClass('mover');},
			mousemove: function(e){if(e.alt == true)this.addClass('mover');}
		});	
	}
});

var selectBoxController = new Class({
	selTable: $empty(),
	container: $empty(),
	scrollLetter: $empty(),
	selSearch: $empty(),
	panelBackBtn: $empty(),
	contData: [],
	calCtrl: {},
	selTips: $empty(),
	initialize: function(table)
	{
		this.selTable = table;
		this.scrollLetter = this.selTable.getElement('#scrollLetter');
		this.selSearch = this.selTable.getElement('#selSearch');
		this.selWrap = this.selTable.getElement('#selWrap');
		this.container = this.selTable.getElement('#selMain');
		this.subCont = this.selTable.getElement('#selSub');
		this.panelBackBtn = this.selTable.getElement('#selPanelBack');
		this.seriesListBtn = this.selTable.getElement('#showContBtn');
		//events
		this.panelBackBtn.addEvent('click', function(e){
			e.preventDefault();
			this.toggleSubCont();
		}.bind(this));
		
		var self = this;
		
		this.seriesListBtn.addEvent('click', function(e){
			e.preventDefault();
			self.calCtrl.deactivate();
			self.srchCtrl.clear();
			
			new Request.JSON({url: api + 'continuing.json',
				onSuccess: function(json){
					this.setContent(json);
					this.selSearch.getElement('input').focus();
				}.bind(self)
			}).send();
		});
				
	},
	setContent: function(content, parentCell){
		this.contData = content;
		this.removeContent();
		if(this.container.st && (typeof this.container.st.tip.destroy == 'function'))
			this.container.st.tip.destroy();
		
		if(!this.contData || !this.contData.length)
			return;
		var self = this;
		var scrollEv = function(){};
		var isSeries = false;
		this.selTips = new Tips({className: 'Tips', showDelay: '1000', fixed: true});	
		var dl = new Element('dl');
		
		this.container.st = new Tips.Pointy({
			pointyTipOptions: {
				point: 3,
				width: 300,
				zIndex: 99,
				className: 'selPointy',
				offset: {x: 10, y: 0}
			}
		});
		
		this.contData.each(function(item){
			var dt = new Element('dt');
			var id = (item.series) ? item.series.id : item.id;
			var name = (item.series) ? item.series.seriesname : item.seriesname;
			
			if(!name)
				return;
				
			var rightcont = new Element('div', {'class' : 'rightcont'}).inject(dt);
					
			if(userstatus.isLoggedin || item.series != null)
			{
				dt.addClass('showRightCont');
				rightcont.set('tween', {duration: 'short'});
				dt.addEvents({
					mouseenter: function(){
						rightcont.tween('marginLeft', -5);
					},
					mouseleave: function(){
						rightcont.tween('marginLeft', -77);
					}
				});
			}			
			var div = new Element('div').inject(dt);
			new Element('a', {html: name}).inject(div);
			div.addEvent('click',function(e){
				e.preventDefault();	
				new seriesPage(name, (item.seasonnumber) ? item.seasonnumber : null, (item.episodenumber) ? item.episodenumber.toInt() : null);				
			});
			
			
			if(!item.series)
			{
				var seText = (item.firstaired != null && item.firstaired != '0000-00-00') ? '/' + new Date().parse(item.firstaired).format('%Y') + '/' : '';
				var span = new Element('span', {text: seText}).inject(dt);
			}
			else {
				isSeries = true;
				var epText = item.seasonnumber + 'x' + sprintf('%02d', item.episodenumber.toInt()) + ' ' + item.episodename;
				var span = new Element('span', {html: epText}).inject(dt);
			}
			
			if(userstatus.isLoggedin && userstatus.preferences.callView == 1 && !item.checked) 
				dt.addClass('notfollowed');
				
			//aired on date
			var airdate_past = (item.firstaired && item.firstaired != '0000-00-00' && ((userstatus.preferences.original_date && new Date().parse(item.firstaired).get('time') < new Date().clearTime()) || (!userstatus.preferences.original_date && new Date().parse(item.firstaired).get('time') < new Date().increment('day', 1).clearTime())));


			var subt = new Element('a', {'class' : 'subt' + ((!airdate_past || !isSeries) ? ' disabled' : ' enabled'), 'html' : 'Felirat keres&eacute;se', rel: 'Felirat keres&eacute;se', href: ((airdate_past && isSeries) ? '#/series/' + escape( name + ' ' + item.seasonnumber + 'x' + sprintf('%02d', item.episodenumber.toInt())) : null) }).inject(rightcont); //subtitle
			if(airdate_past && isSeries)
			{
				this.selTips.attach(subt);
				subt.addEvent('click', function(e){
					e.preventDefault();		
					new subtitlesPage(subt.get('href'));
				});
			}
		
			var tor = new Element('a', {'class' : 'torr' + ((!airdate_past || !isSeries) ? ' disabled' : ' enabled'), 'html' : 'Torrent keres&eacute;se', rel: 'Torrent keres&eacute;se'}).inject(rightcont);
			if(airdate_past && isSeries)
			{
				this.selTips.attach(tor);
				tor.addEvent('click', function(e){
					e.preventDefault();
					self.loadTorrents(item);
					self.toggleSubCont();
				});		
			}

			// end aired on date
		
			//no overview
			if(item.overview && item.overview.length > 0)
			{
				if(item.filename)
					var img = '<span class="imageleft"><img src="/image/episode/' + item.filename + '/150" alt="' + item.episodename + '"></span>';
				else
					var img = '';
				
				dt.store('tip:title', epText).store('tip:text', img + item.overview);
				this.container.st.attach(dt);
			}
		
			//Follow Icon
			var followSeries = new Element('a', {html: 'Sorozat k&ouml;vet&eacute;se', 'rel' : 'Sorozat követése', 'class' : 'followIcon' + (userstatus.isLoggedin ? ((item.checked) ? ' enabled on' : ' enabled off') : ' disabled'), sid: id}).inject(rightcont);
			if(userstatus.isLoggedin)
			{
				this.selTips.attach(followSeries);
				followSeries.addEvent('click', function(){
					new Request({
			        url: api + 'userseries.json|add|' + this.getProperty('sid'),
							onSuccess: function(){
								self.calCtrl.load(parentCell ? parentCell.getProperty('date') :false);
							}
			    }).send();
				});	
			}

		
			//Reviews icon
			var revIco = new Element('a',{
				'class' : 'reviewsIcon' + (isSeries ? ' enabled' : ' disabled'),
				'rel'		: 'Vélemények',
				'html' 	: 'V&eacute;lem&eacute;nyek',
				'href' 	: (item.seasonnumber ? '/e/' + name + "/" + item.seasonnumber + 'x' + sprintf('%02d', item.episodenumber.toInt()) : '#')
			}).inject(rightcont);	
			if(isSeries)	
				this.selTips.attach(revIco);
				
			var downloadedIco = false;
			//Watched icon
			var watchedIco = new Element('a',{
				'class' : 'watchedIcon' + ((!airdate_past || !userstatus.isLoggedin || !isSeries || !item.checked) ? ' disabled' : ' enabled') + (userstatus.isLoggedin ? ((userstatus.userData.user_settings.watchlist && userstatus.userData.user_settings.watchlist.contains(item.id)) ? ' on' : ' off') : ''),
				rel			: 'Megnéztem',
				html 		: 'Megnéztem',
				eid			: item.id
			}).inject(rightcont);		
			if(airdate_past && userstatus.isLoggedin && isSeries && item.checked)
			{
				this.selTips.attach(watchedIco);
				watchedIco.addEvent('click', function(e){
					e.preventDefault();
					new Request.JSON({
			        async: false,
							data: {watchedID: this.getProperty('eid')},
			        url: api + 'userwatched.json|' + ((userstatus.userData.user_settings.watchlist && userstatus.userData.user_settings.watchlist.contains(item.id)) ? 'remove' : 'add'),
							onSuccess: function(json){
								if(json == 'OK')
									if(userstatus.userData.user_settings.watchlist && userstatus.userData.user_settings.watchlist.contains(item.id))
									{
										userstatus.userData.user_settings.watchlist.erase(item.id);
										watchedIco.removeClass('on').addClass('off');
										downloadedIco.addClass('enabled').removeClass('disabled');
									}
									else
									{
										if(!userstatus.userData.user_settings.watchlist)
											userstatus.userData.user_settings.watchlist = [];
										userstatus.userData.user_settings.watchlist.combine([item.id]);
										watchedIco.removeClass('off').addClass('on');
										downloadedIco.addClass('disabled').removeClass('enabled');
									}
									cal.load(parentCell ? parentCell.getProperty('date') :false);

							}
			    }).send();
				});
			}

			//Downloaded icon
			downloadedIco = new Element('a',{
				'class' : 'downloadedIcon' + ((!airdate_past || !userstatus.isLoggedin || !isSeries || !item.checked || (userstatus.userData.user_settings.watchlist && userstatus.userData.user_settings.watchlist.contains(item.id))) ? ' disabled' : ' enabled') + (userstatus.isLoggedin ? ((userstatus.userData.user_settings.downloadlist && userstatus.userData.user_settings.downloadlist.contains(item.id)) ? ' on' : ' off') : ''),
				rel			: 'Letöltöttem',
				html 		: 'Letöltöttem',
				eid			: item.id
			}).inject(rightcont);		
			if(airdate_past && userstatus.isLoggedin && isSeries && item.checked)
			{
				this.selTips.attach(downloadedIco);
				downloadedIco.addEvent('click', function(e){
					e.preventDefault();
					if(!userstatus.userData.user_settings.watchlist || (userstatus.userData.user_settings.watchlist && !userstatus.userData.user_settings.watchlist.contains(item.id)))
					new Request.JSON({
			        async: false,
							data: {downloadedID: this.getProperty('eid')},
			        url: api + 'userdloaded.json|' + ((userstatus.userData.user_settings.downloadlist && userstatus.userData.user_settings.downloadlist.contains(item.id)) ? 'remove' : 'add'),
							onSuccess: function(json){
								if(json == 'OK')
									if(userstatus.userData.user_settings.downloadlist && userstatus.userData.user_settings.downloadlist.contains(item.id))
									{
										userstatus.userData.user_settings.downloadlist.erase(item.id);
										downloadedIco.removeClass('on').addClass('off');
									}
									else
									{
										if(!userstatus.userData.user_settings.downloadlist)
											userstatus.userData.user_settings.downloadlist = [];
										userstatus.userData.user_settings.downloadlist.combine([item.id]);
										downloadedIco.removeClass('off').addClass('on');
									}
									cal.load(parentCell ? parentCell.getProperty('date') :false);
							}
			    }).send();
				});
			}

			rightcont.getElements('a').each(function(el){new Element('span').inject(el);});
			
			dt.inject(dl);	
		}.bind(this));
		dl.inject(this.container);
		
		if(!isSeries)
		{		
			this.selSearch.show();

			scrollEv = function(){
				var deep = dl.getScroll().y;
				var dtz = dl.getElements('dt');
				if(!dtz.length)
					return false;
				var oneh = dtz[0].getSize().y;
				var dttop = Math.floor(deep/oneh);
				if(!content[dttop])
					return false;
				var ltr = content[dttop].seriesname.replace(/^the /i, '').substr(0, 1).toUpperCase();
				var ltr = (/[a-zA-Z]/.test(ltr)) ? ltr : '#';
				this.scrollLetter.set('text', ltr);
			}.bind(this);

			scrollEv();

		}

		new ScScroller(dl, {
			onScroll: scrollEv
		});
		
	},
	toggleSubCont: function(status){
		switch(status)
		{
			default:
				if(this.container.getStyle('left').toInt() == 0)
				{
					this.container.tween('left', -this.container.getSize().x);
					this.subCont.tween('left', 0);
					this.panelBackBtn.show();
				}
				else {
					this.container.tween('left', 0);
					this.subCont.tween('left', this.subCont.getSize().x);
					this.panelBackBtn.hide();
				}		
			break;

			case 1:
				this.container.setStyle('left', 0);
				this.subCont.setStyle('left', this.subCont.getSize().x);
				this.panelBackBtn.hide();
			break;

			case 2:
				this.container.setStyle('left', -this.container.getSize().x);
				this.subCont.setStyle('left', 0);
				this.panelBackBtn.show();
			break;
		}
		
	},
	loadTorrents: function(item)
	{
		var self = this;
		
		var addTorrents = function(json){
			self.subCont.empty();
			if(!json || !json.length)
			{
				new Element('span', {'class' : 'helpText', 'html' : 'Nincs tal&aacute;lat.'}).inject(self.subCont);
				return false;
			}
			var dl = new Element('dl');
			json.each(function(item){
				var dt = new Element('dt');
				var dv = new Element('div', {'class' : 'small'}).inject(dt);
				var a = new Element('a', {'html': item.title, 'href' : item.link}).inject(dv);
				var spn = new Element('span', {'html' : new Date().parse(item.pubDate).format('%Y.%m.%d %H:%M')}).inject(dt);
				dt.inject(dl);
			});
			dl.inject(self.subCont)
		};

			var sname = item.series.seriesname.replace(/\ ?\([^\)]+\)/, '');
			var uri = api + 'torrentsearch.json|' + sname;
			uri += ((item.firstaired != '0000-00-00') ? (userstatus.preferences.original_date) ? '|' + new Date().parse(item.firstaired).format('%Y-%m-%d') : '|' + new Date().parse(item.firstaired).decrement('day', 1).format('%Y-%m-%d') : '');
			uri += ((this.firstaired != '0000-00-00') ? (userstatus.preferences.original_date) ? '|' + new Date().parse(item.firstaired).increment('day', 1).format('%Y-%m-%d') : '|' + new Date().parse(item.firstaired).format('%Y-%m-%d') : '');

		new Request.JSON({
			url: uri,
			onRequest: function(){
				self.selWrap.addSpinner();
			},
			onComplete: function(){
				self.selWrap.removeSpinner();
			},
			onSuccess: addTorrents
		}).send();
	},
	removeContent: function() {
		this.toggleSubCont(1);
		if(this.selTips && 'tip' in this.selTips && (typeof this.selTips.tip.destroy == 'function'))
			this.selTips.tip.destroy();
		this.container.empty();
		this.selSearch.hide();
		this.scrollLetter.empty();
	}
});

var searchController = new Class({
	initialize: function(s, sel, cal)
	{
		this.calCtrl = cal;
		this.selCtrl = sel;
		this.selCtrl.srchCtrl = this;
		this.calCtrl.srchCtrl = this;
		
		this.searchField = s.getElement('.searchField > input');
		this.placeholder = s.getElement('span.placeholder');
		this.searchBtn = s.getElement('#searchBtn');
		this.searchTypeSelect = s.getElement('#searchSelect');
		this.sLabel = s.getElement('label');
		
		//events
		var self = this;
		
		this.sObserver = new Observer(this.searchField, function(val, el){
			this.calCtrl.deactivate();
			
			if(val.length < 3){
				this.searchBtn.removeClass('searchClear');
				return this.selCtrl.setContent(null);
			}
			else {
				this.searchBtn.addClass('searchClear');
			}
			
			this.startSearch(val);
			
		}.bind(this)).pause();
		
		this.searchField.addEvents({
			focus: function(){
				self.sObserver.resume();
				self.sLabel.addClass('focus');
				if(self.placeholder.isDisplayed())
					self.placeholder.hide();
			},
			blur: function(){
				self.sObserver.pause();
				self.sLabel.removeClass('focus');
				if(!this.get('value').length)
					self.placeholder.show();
			},
			keyup: function(e){
				if(e.key == 'esc'){
					this.clear();
					this.selCtrl.setContent(null);
				}
			}.bind(this)
		});
		
		this.searchBtn.addEvent('click', function(e){
			e.preventDefault();
			if(this.hasClass('searchClear')){
				self.clear();
				self.selCtrl.setContent(null);		
			}
		});
		
		new FauxSelect(this.searchTypeSelect, {
			triggerEvent: 'contextmenu',
			triggerElement: this.searchBtn,
			onChange: function(val, text){
				this.placeholder.set('html', 'Keres&eacute;s: ' + text.toLowerCase() + '...');
			}.bind(this)
		});
		this.searchTypeSelect = $('searchSelect');
		this.shortcuts();
		this.setSelSearch();
	},
	clear: function(){
		this.searchField.set('value', '');
		this.searchField.fireEvent('blur');
		this.searchField.blur();
		this.searchBtn.removeClass('searchClear');
	},
	shortcuts: function(){
		var focusSField = function(e){
			e.preventDefault();
			this.searchField.focus();
		};

		this.keyboard = new Keyboard({
	    defaultEventType: 'keydown'
		});
		
		switch(Browser.Platform)
		{
			case "mac":
				this.keyboard.addShortcut('search',{
					keys : 'command+f',
					description: 'Sorozat keresése',
					handler: focusSField.bind(this)
				});
			break;
			
			default:
				this.keyboard.addShortcut('search',{
					keys : 'ctrl+f',
					description: 'Sorozat keresése',
					handler: focusSField.bind(this)
				});
			break;
		}
	},
	startSearch: function(word){
		new Request.JSON({url: api + 'searchseries.json|' + this.searchTypeSelect.get('value') + '|' + word,
			onRequest: function(){
				this.searchBtn.addClass('spinnerBlk');
			}.bind(this),
			onSuccess: function(json, text){
				this.selCtrl.setContent(json);
				if(typeOf(json) != 'array' || !json.length)
					new Element('span.helpText', {html: 'Nincs tal&aacute;lat.'}).inject(this.selCtrl.container);
			}.bind(this),
			onComplete: function(){
				(function(){this.searchBtn.removeClass('spinnerBlk');}).delay(500, this);
			}.bind(this),
			onFailure: function(){
				this.selCtrl.removeContent();
				new Element('span.helpText', {html: 'Nincs tal&aacute;lat.'}).inject(this.selCtrl.container);
			}.bind(this)
		}).send();
	},
	setSelSearch: function(){
		var self = this;
		var delknob = this.selCtrl.selSearch.getElement('a');
		var selInp = this.selCtrl.selSearch.getElement('input');
		
		delknob.addEvent('click', function(e){
			e.preventDefault();		

			var dl = self.selCtrl.container.getElement('dl');
			if(!dl)
				return;		
			var dts = self.selCtrl.container.getElements('dl > dt');
			if(!dts.length)
				return false;
			dts.show();

			selInp.set('value', '');
			selInp.blur();		
			dl.update();
			this.fade('hide');	
		});
		
		selInp.addEvent('keyup', function(e){
			var val = this.get('value');
			
			var dl = self.selCtrl.container.getElement('dl');
			if(!dl)
				return;
			var dts = self.selCtrl.container.getElements('dl > dt');
			if(!dts.length)
				return false;
			dts.show();

			if(val.length)
				delknob.fade('show');
			else
				delknob.fade('hide');

			switch(e.key)
			{
				default:
					if(!val.length)
					{
						dl.update();	
						return false;
					}
					dts.each(function(elem){
						if(!elem.getElement('div:not([class])>a:not([sid])').get('text').toLowerCase().test(val.toLowerCase()))
							elem.hide();
					});
					dl.update();
				break;

				case 'esc':
					this.set('value', '');
					this.blur();
					dl.update();
					delknob.fade('hide');
				break;
			}
		});
	}
});

var subtitlesPage = new Class({
	box: $empty(),
	container: $empty(),
	searchFor: '',
	baseUrl: 'http://felirat.mitnezel.net/',
	initialize: function(searchFor){
		if(typeof openSubpage == 'object')
			openSubpage.dispose(true);
		openSubpage = this;
		
		if(typeof cal == 'object')
		{
			this.calCtrl = cal;
			this.calCtrl.keyboardShortcuts.deactivate();
		}
		
		this.searchFor = searchFor;
		this.container = $(document.body);
		this.loadPage();
		this.shortcuts();
	},
	loadPage: function(){
		var self = this;
		document.getElement('html').addClass('nofollow');

		var lightsOn = (Cookie.read('sc_lightsOn') || 0).toInt();
		 
		this.box = new Element('div', {'class' : 'seriaBox subtitleBox' + ((lightsOn) ? '' : ' black')}).fade('hide');
		this.page = new Element('div', {'class' : 'seriaPage'}).inject(this.box);
		
		var logo = new Element('div', {'class' : 'logo', html: 'Mit n&eacute;zel?'}).inject(this.page);
		this.lightSwitchElement = new Element('a', {'title' : 'Villanykapcsoló (⌃L)', 'html' : 'Villanykapcsoló (⌃L)', 'class' : 'ir' + ((lightsOn) ? ' on' : '')})
		.inject(logo)
		.addEvent('click', function(e){
			e.preventDefault();
			self.lightSwitch();
		});
		

		var topBtnCont = new Element('div', {'class' : 'topBtnCont'}).inject(this.page);
		
		var totopbtn = new Element('a', {'class' : 'toTopBtn', href: '#top', html: 'Tetejére'}).inject(topBtnCont);
		var closebtn = new Element('a', {'class' : 'closebtn', html: 'Bez&aacute;r&aacute;s'})
		.inject(topBtnCont)
		.addEvent('click', function(){
			self.dispose();
		});
		
		this.wrap = new Element('div', {'class' : 'wrap'}).inject(this.page);
		
		this.iframeElement = new Element('iframe',{
			src: this.baseUrl + this.searchFor,
			events: {
				load: function(){
					if(typeOf(this.contentWindow.postMessage) == 'function')
						this.contentWindow.postMessage('formitnezel', self.baseUrl);	
				}
			}
		}).inject(this.wrap);
		
		this.box.inject(this.container, 'bottom');
		this.box.fade('in');
		
	},
	dispose: function(withoutAnimation){	
		var dispose = function(){
			if(this.calCtrl)
				this.calCtrl.keyboardShortcuts.activate();
			this.box.dispose();

			document.getElement('html').removeClass('nofollow');

			openSubpage = $empty();
		}.bind(this);
		if(withoutAnimation)
			dispose();
		else
		new Fx.Tween(this.box, {property: 'opacity'}).start(1, 0).chain(dispose);
	},
	shortcuts: function(){
		this.keyboardShortcuts = new Keyboard({
		    defaultEventType: 'keydown', 
		    events: { 
					'ctrl+l' : this.lightSwitch.bind(this)
				}
		});
	},
	lightSwitch: function(){
		this.lightSwitchElement.toggleClass('on');
		this.box.toggleClass('black');
		Cookie.write('sc_lightsOn', ((this.box.hasClass('black')) ? 0 : 1), {duration: 14, path: '/'});
	}
});

var setBtmPanel = function(){
	$$('#mostPopularSeries > li > a').each(function(elem){
		var id = elem.get('href').substr(1);
		elem.removeProperty('href');
		elem.addEvent('click', function(e){
			e.preventDefault();			
			new seriesPage(id);
		});	
	})
};

var cal, sel, srchC, cS;
window.addEvent('domready', function(){
	sel = new selectBoxController($('selTable'));
	cal = new calendarController($('calMain'), $('calTable'), sel);
	srchC = new searchController($('selHeader'), sel, cal);

	setBtmPanel();
	
	userstatus = new updateUserStatus({
		onLogin: function(){
			$('showContBtn').fade('show');
			// if(cS)
			// 	cS.dispose();
			if(!cS)
			cS = new sliderRadio($('calSwitch'),{
				onChange: function(val){
					new Request.JSON({
						async: true,
						url: api + 'userCalView.json|' + val,
						onSuccess: function(json){
							if(json == 'OK')
							{
								userstatus.updateStatus();
							}
						}
					}).send();
				},
				initialStep: ('callView' in userstatus.preferences) ? userstatus.preferences.callView : 0
			});
			$('calSwitch').show();
			$$('.ifanonymous').hide();
		},
		onLogout: function(){
			$('showContBtn').fade('hide');
			if(cS)
			{
				cS.dispose();
				$('calSwitch').hide();
			}
			$$('.ifanonymous').show('inline');
		},
		onOther: function(){
			cal.load();
		}	
	});
});